﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.Linq;
using System.Xml.Linq;
using WPFExcelReport.Helpers;
using ConsoleClient;
namespace WPFExcelReport
{
    public class Agent
    {
        public Agent()
        {
        }
        public Agent(string id)
        {
            ID = "AGETNID" + id;
            time = DateTime.Now;
        }
        public bool IsRun = false;
        public bool IsListening = false;
        public string ID;
        public DateTime time;
        public DataSet dsResult;
        public SqlDataAdapter mySqlDa;
        public OracleCommand Command;
        public string Connection = "";
        public OracleDataAdapter DataAdapter;
        public string State = "Query";
        public bool IsOnTransation = false;
        //public IIntexReptServBLCallback CallBack;
        public void StartTransation()
        {
            if (Command == null)
                return;
            if (Command.Connection.State == ConnectionState.Closed)
                Command.Connection.Open();
            Command.Transaction = Command.Connection.BeginTransaction(IsolationLevel.ReadCommitted);
            IsOnTransation = true;

        }
        private string itxsrv;
        public int itxport;
        ITXCLIENT _itxclient;
        public ITXCLIENT itxclient
        {
            get
            {
                if(_itxclient==null)
                {
                    _itxclient = new ITXCLIENT();
                    _itxclient.Server = itxsrv;
                    _itxclient.Port = itxport;
                    _itxclient.Connect();
                }
                return _itxclient;
            }
        }
        public void StartItxClient()
        {
           
        }
        public void RollBack()
        {
            Command.Transaction.Rollback();
            IsOnTransation = false;
            Command.Connection.Close();
        }
        public void Commit()
        {
            Command.Transaction.Commit();
            IsOnTransation = false;
            Command.Connection.Close();
        }
        public void SetUpOracle(Dictionary<string, object> dicSrcParamater)
        {
            Connection = (string)dicSrcParamater["ConnectionString"];
            string CommandT = (string)dicSrcParamater["CommandType"];
            if (Command != null)
            {
                int pc = Command.Parameters.Count;
                for (int i = 0; i < pc; i++)
                {
                    Command.Parameters.RemoveAt(0);
                }
                if (Command.Connection.ConnectionString.Trim() == Connection.Trim())
                {
                    if (Command.Connection.State == ConnectionState.Closed)
                    {
                        Command.Connection.Open();
                    }

                }
                if (CommandT == "StartTransation")
                {
                    StartTransation();
                    State = "Transation";
                }
                if (CommandT == "Commit")
                {
                    Commit();
                    State = "Transation";
                }
                if (CommandT == "RollBack")
                {
                    RollBack();
                    State = "Transation";
                }
                if (CommandT == "Text")
                {
                    State = "Query";
                }

                return;
            }
            Command = new OracleCommand();
            Command.CommandType = CommandType.Text;

            foreach (KeyValuePair<string, object> kvp in dicSrcParamater)
            {
                switch (kvp.Key)
                {
                    case "DBTYPE":
                    case "DataTable":
                    case "AGENTID":
                    case "CommandType":
                        break;
                    case "CommandText":
                        Command.CommandText = (string)dicSrcParamater["CommandText"];
                        break;
                    case "ConnectionString":

                        Connection = (string)dicSrcParamater["ConnectionString"];

                        if (Command.Connection == null)
                        {
                            Command.Connection = new OracleConnection(Connection);
                        }
                        if (Command.Connection.State == ConnectionState.Closed)
                            Command.Connection.Open();
                        break;
                    default:
                        break;
                }
            }
        }
        public void CloseDB()
        {
            if (Command.Connection.State == ConnectionState.Open)
                Command.Connection.Close();
        }
       
        public DataSet GetDataSetByQuery(Dictionary<string, object> args)
        {
            DataSet dsResult = new DataSet();
            OracleParameter catCMDP;

            string commandtype = "CommandText";
            string strCommandType;
            string dbType = "Oracle";
            if (args.ContainsKey("DBTYPE"))
            {
                dbType = args["DBTYPE"].ToString();
            }
            SqlParameter sqlParameter;
            string tb = "Table";
            switch (dbType)
            {
                case "ITXCLIENT":
                    dsResult = GetDataByITX(args);
                    break;
                case "ORACLEBLOB":
                    #region===ORACLEBLOB==========
                    SetUpOracle(args);
                    if (State == "Transation")
                    {
                        return dsResult;
                    }
                     foreach (KeyValuePair<string, object> kvp in args)
                    {
                        switch (kvp.Key)
                        {
                            case "DBTYPE":
                            case "AGENTID":
                            case "ConnectionString":
                                break;
                            case "DataTable":
                                tb = (string)args["DataTable"];
                                break;
                            case "CommandType":
                                strCommandType = (string)args["CommandType"];
                                switch (strCommandType)
                                {
                                    case "StoredProcedure":
                                        Command.CommandType = CommandType.StoredProcedure;
                                        commandtype = "StoredProcedure";
                                        break;
                                    case "TableDirect":
                                        Command.CommandType = CommandType.TableDirect;
                                        commandtype = "TableDirect";
                                        break;
                                    default:
                                        Command.CommandType = CommandType.Text;
                                        break;
                                }
                                break;
                            case "CommandText":
                                Command.CommandText = (string)args["CommandText"];
                                break;
                            default:
                                catCMDP = new OracleParameter();
                                catCMDP.ParameterName = kvp.Key;
                                catCMDP.Direction = ParameterDirection.Input;
                                catCMDP.OracleType = OracleType.Blob;
                                catCMDP.Value = kvp.Value;
                                Command.Parameters.Add(catCMDP);
                                break;
                        }
                    }
                    if (commandtype == "StoredProcedure")
                    {
                        //Tracer.Verbose("Service", "StoredProcedure");
                        //MessageBox.Show("Dear Sir," + "StoredProcedure");
                        Command.ExecuteNonQuery();
                        Command.Connection.Close();
                        return dsResult;
                    }
                    if (Command.CommandText.StartsWith("UPDATE")
                        || Command.CommandText.StartsWith("INSERT")
                        || Command.CommandText.StartsWith("DELETE")
                         )
                    {
                        Command.ExecuteNonQuery(); ;
                        return dsResult;
                    }

                    if (DataAdapter == null)
                    {
                        DataAdapter = new OracleDataAdapter(Command);
                        DataAdapter.ContinueUpdateOnError = true;
                    }
                    DataAdapter.Fill(dsResult);
                    dsResult.Tables[0].TableName = tb;
                    break;
                    #endregion
                    break;
                case "SQLSERVER":
                    #region=====SQLSERVER======== 
                    dsResult = SQLHelper.GetData(args);
                    break;
                #endregion
                case "ORACLE":
                default:
                    #region===ORACLE==========
                    SetUpOracle(args);
                    if (State == "Transation")
                    {
                        return dsResult;
                    }
                    foreach (KeyValuePair<string, object> kvp in args)
                    {
                        switch (kvp.Key)
                        {
                            case "DBTYPE":
                            case "AGENTID":
                            case "ConnectionString":
                                break;
                            case "DataTable":
                                tb = (string)args["DataTable"];
                                break;
                            case "CommandType":
                                strCommandType = (string)args["CommandType"];
                                switch (strCommandType)
                                {
                                    case "StoredProcedure":
                                        Command.CommandType = CommandType.StoredProcedure;
                                        commandtype = "StoredProcedure";
                                        break;
                                    case "TableDirect":
                                        Command.CommandType = CommandType.TableDirect;
                                        commandtype = "TableDirect";
                                        break;
                                    default:
                                        Command.CommandType = CommandType.Text;
                                        break;
                                }
                                break;
                            case "CommandText":
                                Command.CommandText = (string)args["CommandText"];
                                break;
                            default:
                                catCMDP = new OracleParameter();
                                catCMDP.ParameterName = kvp.Key; 
                                catCMDP.Value = (string)kvp.Value;
                                Command.Parameters.Add(catCMDP);
                                break;
                        }
                    }
                    if (commandtype == "StoredProcedure")
                    {
                        //Tracer.Verbose("Service", "StoredProcedure");
                        //MessageBox.Show("Dear Sir," + "StoredProcedure");
                        Command.ExecuteNonQuery();
                        Command.Connection.Close();
                        return dsResult;
                    }
                    if (Command.CommandText.StartsWith("UPDATE")
                        || Command.CommandText.StartsWith("INSERT")
                        || Command.CommandText.StartsWith("DELETE")
                         )
                    {
                        Command.ExecuteNonQuery(); ;
                        return dsResult;
                    }

                    if (DataAdapter == null)
                    {
                        DataAdapter = new OracleDataAdapter(Command);
                        DataAdapter.ContinueUpdateOnError = true;
                    }
                    DataAdapter.Fill(dsResult);
                    dsResult.Tables[0].TableName = tb;
                    break;
                    #endregion
            }
            return dsResult;
        }
        public DataSet GetDataByITX(Dictionary<string, object> args)
        {
            itxsrv= (string)args["ITXSRV"];
            itxport = (int)args["ITXPORT"];
            string transaction = (string)args["TRANS"];
            string cmd = (string)args["COMMAND"];
            string datamap = (string)args["DATAMAP"];
            return itxclient.Commnicate(transaction, cmd); 
        } 
    }
}